package com.fanshuai.spring.boot.local.spring.service;

import com.fanshuai.spring.boot.local.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class UserService {
    @Resource
    private JdbcTemplate template1;
    @Resource
    private JdbcTemplate template2;

    @Resource
    private DataSourceTransactionManager transactionManager;
    @Resource(name = "transactionManager2")
    private DataSourceTransactionManager transactionManager2;
    @Resource
    private TransactionDefinition definition;

    public boolean batchAdd(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return true;
        }

        TransactionStatus status = null;
        boolean b = true;
        try {
            status = transactionManager.getTransaction(definition);
            for (User user : userList) {
                int rows = template1.update("insert into user(name) value (?)", user.getName());
                b = b && rows > 0;
            }

            if (b) {
                transactionManager.commit(status);
            } else {
                transactionManager.rollback(status);
            }
        } catch (Exception e) {
            log.error(e + "");
        } finally {
            if (null != status && !status.isCompleted()) {
                transactionManager.rollback(status);
            }
        }

        return b;
    }

    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager2")
    public boolean batchAdd2(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return true;
        }

        boolean b = true;
        for (User user : userList) {
            int rows = template2.update("insert into user(name) value (?)", user.getName());
            b = b && rows > 0;
        }
        if (!b) {
            throw new RuntimeException("save error");
        }
        return b;
    }
}
